#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024-05-17 15:13
# @Author  : nedncs
# @File    : run.py
# @Description : src/python_ldap_admin/core/ldap

from ldap3 import Connection, Server, ServerPool, SUBTREE, ALL, MODIFY_REPLACE

import utils.RSADecrypt as rsa

LDAP_SERVER_POOL = ['192.168.100.229']
LDAP_SERVER_PORT = 389
ADMIN_DN = 'cn=admin,dc=yxxglass,dc=com'
ADMIN_PASSWORD = 'Asdqq424132'
SEARCH_BASE = 'ou=people,dc=yxxglass,dc=com'


def ldap_auth(username, password):
    """ldap验证用户"""
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool, user=ADMIN_DN, password=ADMIN_PASSWORD, check_names=True, lazy=False,
                      raise_exceptions=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base=SEARCH_BASE,
        search_filter='(uid={})'.format(username),
        search_scope=SUBTREE,
        attributes=['cn', 'givenName', 'mail', 'uid', 'userpassword'],
        paged_size=5
    )

    if res:
        entry = conn.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']
        conn.unbind()
        # check password by dn
        try:
            passwd_code = attr_dict['userPassword'][0].decode('utf-8')
            # passwd_txt = rsa.rsa_decrypt(passwd_code)
            passwd_txt = passwd_code
            if passwd_txt != password:
                return False, None, None, None
            conn2 = Connection(ldap_server_pool, user=dn, password=passwd_code, check_names=True, lazy=False,
                               raise_exceptions=False)
            conn2.bind()
            res = conn2.result
            conn2.unbind()
            if res["description"] == "success":
                print((True, attr_dict["mail"], attr_dict["uid"], attr_dict["givenName"]))
                return (True, attr_dict["mail"], attr_dict["uid"], attr_dict["givenName"])
            else:
                print("auth fail")
                return (False, None, None, None)
        except Exception as e:
            print("auth fail")
            return (False, None, None, None)

    else:
        return (False, None, None, None)


def auth_change_password(username, new_password):
    ldap_server_pool = ServerPool(LDAP_SERVER_POOL)
    conn = Connection(ldap_server_pool, user=ADMIN_DN, password=ADMIN_PASSWORD, check_names=True, lazy=False,
                      raise_exceptions=False)
    conn.open()
    conn.bind()

    res = conn.search(
        search_base=SEARCH_BASE,
        search_filter='(uid={})'.format(username),
        search_scope=SUBTREE,
        attributes=['cn', 'givenName', 'mail', 'uid', 'userpassword'],
        paged_size=5
    )
    if res:
        entry = conn.response[0]
        dn = entry['dn']
        attr_dict = entry['attributes']

        # check password by dn
        try:
            changes = {'userPassword': [(MODIFY_REPLACE, [new_password.encode()])]}
            conn.modify(dn, changes)
            res = conn.result
            if res["description"] == "success":
                print((True,  attr_dict["uid"]))
                return (True, attr_dict["uid"])
            else:
                print("auth fail")
                return (False, None, None, None)
        except Exception as e:
            print("auth fail", e)
            return (False, None, None, None)
    else:
        return (False, None, None, None)
